<?php

/**
 * 封装一个数据库操作类
 */
class db {
	public $pdo;
	public $host;
	public $port;
	public $dbname;
	public $user;
	public $pass;

	function __construct($config) {
		$this->host = $config['host'];
		$this->port = $config['port'];
		$this->dbname = $config['dbname'];
		$this->user = $config['user'];
		$this->pass = $config['pass'];

		$this->connect_db();
	}

	// 连接数据库
	function connect_db() {
		try {
			$pdo = new PDO('mysql:host=' . $this->host . ';port=' . $this->port . ';dbname=' . $this->dbname, $this->user, $this->pass);
			// 设置编码utf8;
			$pdo->exec('set names utf8');
			$this->pdo = $pdo;
			// $sql = 'INSERT INTO `tb_scoreinfo`(`sno`, `sname`, `chinesescore`, `englishscore`, `mathscore`, `physicsscore`, `chemistryscore`) VALUES (004, "刘麻子", 82, 91, 60, 83, 76)';
			// $this->pdo->exec($sql);
		} catch (Exception $e) {
			print "Error" . $e->getMessage() . '<br />';
			die;
		}
	}

	// 插入数据
	function add($sql) {
		$res = $this->pdo->exec($sql);
		if ($res) {
			return true;
		} else {
			// echo "添加失败";
			return false;
		}
	}
	//查询数据
	function find($sql) {
		$res = $this->pdo->query($sql);
		$data = [];
		while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
			$data[] = $row;
		}
		return $data;

	}

	//更新数据
	function update($sql) {
		$res = $this->pdo->exec($sql);
		if ($res) {
			//echo '更新数据成功，更新数据条数：'.$res->rowCount().'<br/>';
			return $res; //true
		} else {
			//$this->error();
			//echo '更新失败！';
			return false;
		}

	}

	//删除数据
	function del($sql) {
		$res = $this->pdo->exec($sql);
		if ($res) {
			//echo '删除数据成功<br/>';
			return $res;
		} else {
			//$this->error();
			return false;
		}

	}

	//错误输出
	function error() {

		$error = $this->pdo->errorInfo();
		var_dump($error);exit;

	}
}

?>